<template>
 <div>
    <!-- 查询条件 -->
    <div class="orderactivity-header">
      <div class="assign-header">
        <div class="d2-mb-20">绑定人脸设备</div>
        <i class="el-icon-close" style="font-size: 20px; color: #72767b;" @click="close"></i>
      </div>
    </div>
    <el-divider></el-divider>
    <div class="contacts-content">
      <main-table :columns="columns" :data="tableList" :isPaginationShow="false" @getData="fetchTableList" :loading="loading" wrapperHeight="calc(100vh - 100px)">
        <!-- wrapperHeight：父元素高度根据实际布局情况配置，大多情况可能是 外层祖父元素高度 减去 其他兄弟元素的高度，如果外层祖父元素高度或者兄弟元素的高度不固定，可能需要借助 js来计算 -->
        <el-table-column slot="status" label="绑定状态" align="center" width="120">
          <template slot-scope="scope">
            <el-tag class="tag-cursor" v-if="scope.row.status == '1'" type="success">已绑定</el-tag>
            <el-tag class="tag-cursor" v-else type="danger">未绑定</el-tag>
          </template>
        </el-table-column>
        <el-table-column slot="action" fixed="right" label="操作" width="150">
          <template slot-scope="scope">
             <el-button class="button-view-color" v-if="scope.row.status == '1'" size="mini" type="danger" @click="unbind(scope.row)">解绑</el-button>
            <el-button class="button-edit-color" v-else size="mini" type="success" @click="bind(scope.row)"></i>绑定</el-button>
          </template>
        </el-table-column>
      </main-table>
    </div>
  </div>
</template>
<script>
import mainTable from "@/components/main-table/index";
import * as APISystem from '@/api/system'
import { sex, age, elderlyCategory, sourceType, unixToDate } from "@/utils";
import { getUserInfo } from "@/api/user";
import { mapState } from 'vuex'
import store from "@/store";
export default {
  props: {
    data: {
      type: Object,
      default: () => {}
    }
  },
  components: { mainTable },
  data () {
    return {
      // 查询条件
      searchForm: {
        page: 1
      },
      dialogVisible: false,
      // 员工loading
      columns: [
        {
          index: true
        },
        {
          prop: 'name',
          label: '设备名称'
        },
        {
          prop: 'team_name',
          label: '负责站点'
        },
        {
          prop: 'device_sn',
          label: '人脸设备号'
        },
        {
          slot: 'status'
        },
        {
          prop: 'type',
          label: '设备类型',
          width: 120,
          formatter (row, column, cellValue) {
            if (cellValue == '1') {
              return '活动设备'
            } else if (cellValue == '2') {
              return '食堂设备'
            }
          }
        },
        {
          prop: 'create_time',
          label: '创建时间',
          width: 210,
          formatter (row, column, cellValue) {
            return unixToDate(cellValue)
          }
        },
        {
          slot: 'action'
        }
      ],
      tableList: [],
      pagination: {
        current: 1,
        size: 15,
        total: 0
      },
      loading: false,
      is_bind:[]
    }
  },
  mounted () {
    this.fetchTableList()
  },
  methods: {
    // 关闭弹窗
    close () {
      this.$emit('cancle')
    },
    // 手动清空/搜索
    clear () {
      this.fetchTableList()
    },
    setItemUserdata(){
      let hasToken = store.getters["user/accessToken"];
      getUserInfo(hasToken).then((res) => {
        const { data } = res;
        if (!data) {
          Vue.prototype.$baseMessage("验证失败，请重新登录...", "error");
          return false;
        }
        localStorage.setItem("userdata", JSON.stringify(data)) 
      })
    },
    bind (row) {
      if(this.is_bind && this.is_bind.length != 0){
        this.$message({ type: "error", message: "人脸设备只能绑定一个!"});
        return false;
      }
      APISystem.facedevBind({ device_sn: row.device_sn, admin_id: this.data.id }).then(() => {
        this.fetchTableList();
        this.setItemUserdata();
        this.$message({ type: "success", message: "绑定成功!"});
      })
    },
    unbind (row) {
      APISystem.facedevUnbind({ device_sn: row.device_sn, admin_id: this.data.id }).then(() => {
        this.fetchTableList();
        this.setItemUserdata();
        this.$message({ type: "success", message: "解绑成功!"});
      })
    },
    // 获取数据
    fetchTableList (pageObj) {
      this.loading = true
      this.searchForm = {
        ...this.searchForm,
        ...pageObj
      }
      const _this = this;
      _this.is_bind = [];
      APISystem.facedevList(this.searchForm).then((res) => {
        const { list = [] } = res.data;
        if (list.length === 0) {
          this.tableList = []
        } else {
          APISystem.facedevMybind({ admin_id: this.data.id }).then(data => {
            _this.is_bind = data['data'].info;
            if (data['data'].info && data['data'].info.length != 0) {
              list.forEach((item, index) => {
                _this.$set(list[index], 'status', '0')
                data['data'].info.forEach(ite => {
                  if (item.device_sn == ite.device_sn) {
                    _this.$set(list[index], 'status', '1')
                  }
                })
              })
              this.tableList = list
            } else {
              list.forEach((item, index) => {
                _this.$set(list[index], 'status', '0')
              })
              this.tableList = list
            }
          }).catch(() => {
            list.forEach((item, index) => {
              _this.$set(list[index], 'status', '0')
            })
            this.tableList = list
          })
        }
      }).finally(() => {
        this.loading = false
      })
    },
    // 点击”查询“按钮 => 此时缓存查询参数
    onSearch () {
      this.pagination = {
        current: 1,
        size: 15,
        total: 0
      }
      this.fetchTableList()
    },
    // 重置
    onReset () {
      this.$refs.searchForm.resetFields()
      this.fetchTableList()
    }
  }
}
</script>
<style lang="scss" scoped>
  .assign-header {
    display: flex;
    justify-content: space-between;
    cursor: pointer;
  }
  .orderactivity-header{
     padding: 20px;
     padding-bottom: 0px;
  }
  .contacts-content {
   padding: 0 20px;
   padding-bottom: 7px;
  }
</style>
